import os
import logging
from datetime import datetime
from config import ROOT_DIR

class Logger:
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(Logger, cls).__new__(cls)
            cls._instance._initialize_loggers()
        return cls._instance

    def _initialize_loggers(self):
        """初始化日志配置"""
        # 创建logs目录 - 使用ROOT_DIR确保路径正确
        log_dir = os.path.join(ROOT_DIR, 'logs')
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
        
        # 获取当前日期
        current_date = datetime.now().strftime('%Y%m%d')
        
        # 配置常规日志
        info_log_file = os.path.join(log_dir, f'info_{current_date}.log')
        self.info_logger = logging.getLogger('info_logger')
        self.info_logger.setLevel(logging.INFO)
        
        info_handler = logging.FileHandler(info_log_file, encoding='utf-8')
        info_handler.setFormatter(logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        ))
        self.info_logger.addHandler(info_handler)
        
        # 配置错误日志
        error_log_file = os.path.join(log_dir, f'error_{current_date}.log')
        self.error_logger = logging.getLogger('error_logger')
        self.error_logger.setLevel(logging.ERROR)
        
        error_handler = logging.FileHandler(error_log_file, encoding='utf-8')
        error_handler.setFormatter(logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        ))
        self.error_logger.addHandler(error_handler)

    def info(self, message):
        """记录信息日志"""
        self.info_logger.info(message)

    def error(self, message):
        """记录错误日志"""
        self.error_logger.error(message)

# 创建全局logger实例
logger = Logger()
